package com.zhangyj.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.SqlSession;

import com.zhangyj.BoastException;
import com.zhangyj.LocalMessage;
import com.zhangyj.dao.DaoManager;
import com.zhangyj.data.BUserMapper;
import com.zhangyj.data.tables.BUser;
import com.zhangyj.entitis.User;
import com.zhangyj.impl.UserContext;
import com.zhangyj.util.AlgorithmUtil;
import com.zhangyj.util.Tools;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = -5434535570752440408L;
	private String secess = "work.index";
	private String loginout = "work.loginout";

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = Tools.getParameter(request, "action", "login");
		String returnPath = this.secess;
		if (action.equals("login")) {
			returnPath = login(request, response);
		} else if ("out".equals(action)) {
			returnPath = loginOut(request, response);
		}
		response.sendRedirect(returnPath);
	}

	public String loginOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().removeAttribute(UserContext.key);
		Cookie cs[] = request.getCookies();
		for (int i = 0; i < cs.length; i++) {
			Cookie c = cs[i];
			if (c.getName().equals("_ssid")) {
				c.setMaxAge(0);
				response.addCookie(c);
				break;
			}
		}
		return loginout;
	}

	String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String lgnName = request.getParameter("loginname");
		if (lgnName == null) {
			return tologinPage(request);
		}

		request.setAttribute("loginname", lgnName);
		String password = request.getParameter("password");

		String validateCode = request.getParameter("validatecode");
		HttpSession session = request.getSession();

		String sessionValiCode = (String) session.getAttribute(Tools.VALIDATE_KEY);
		if (validateCode == null || !validateCode.equalsIgnoreCase(sessionValiCode)) {

			request.setAttribute("error", LocalMessage.get("error.validatecode"));
			return tologinPage(request);

		}
		if (lgnName == null || lgnName.isEmpty()) {
			request.setAttribute("error", LocalMessage.get("error.isnotnull", new String[] { LocalMessage.get("username") }));
			return tologinPage(request);

		}

		try {
			SqlSession ss = DaoManager.getSqlSession();
			BUserMapper mapper = ss.getMapper(BUserMapper.class);
			BUser buser = mapper.selectByLgnname(lgnName);
			//UserDao dao = DaoManager.getDao(UserDao.class);
			//User user = dao.loadUserFromLoginName(lgnName);
			password = AlgorithmUtil.md5Digest(AlgorithmUtil.desEncrypt(password.getBytes(), AlgorithmUtil.fieldDesKey));
			if (buser != null && buser.getUserPassword() != null && buser.getUserPassword().equals(password)) {
				UserContext userContext = new UserContext(buser.getUserId(),buser.getLgnname(), buser.getUsername(),buser.getUserId());
				UserContext.setUserContext(request, userContext);
			} else {
				request.setAttribute("error", LocalMessage.get("error.loginFail"));
				return tologinPage(request);
			}
		} catch (Exception e) {
			throw new ServletException(e);
		}
		String returnPath = Tools.getParameter(request, "returnPath", "");
		if (returnPath.length() > 0) {
			return returnPath;
		}
		String ssid = AlgorithmUtil.desEncryptToString(lgnName.getBytes(), AlgorithmUtil.fieldDesKey);
		Cookie c = new Cookie("_ssid", ssid);
		c.setPath("/");
		c.setMaxAge(-1);
		response.addCookie(c);
		return this.secess;
	}

	String tologinPage(HttpServletRequest request) throws BoastException {
		String returnPath = Tools.getParameter(request, "returnPath", "");
		request.setAttribute("returnPath", returnPath);
		return "/login.jsp";
	}

}
